package com.northwest_man.refactor_tool;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MultiLanguageMissingTranslationsFinder {

    // 读取strings.xml并提取所有的key和对应的value，跳过带translatable="false"的项和值以@string/开头的项
    private static Map<String, String> extractKeysAndValuesFromStringsFile(File xmlFile) {
        Map<String, String> keyValues = new HashMap<>();
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("string");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NamedNodeMap attributes = node.getAttributes();

                // 检查是否有translatable属性且值为false
                Node translatableNode = attributes.getNamedItem("translatable");
                if (translatableNode != null && "false".equals(translatableNode.getNodeValue())) {
                    continue; // 跳过此项
                }

                String key = attributes.getNamedItem("name").getNodeValue();
                String value = node.getTextContent();

                // 跳过值以@string/开头的项
                if (value.startsWith("@string/")) {
                    continue;
                }

                keyValues.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return keyValues;
    }

    // 读取待排除的key文件
    private static Set<String> loadExcludedKeys(File excludeFile) {
        Set<String> excludedKeys = new HashSet<>();
        try {
            if (excludeFile.exists()) {
                excludedKeys.addAll(Files.readAllLines(excludeFile.toPath()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return excludedKeys;
    }

    // 比较默认语言和多个目标语言的keys和values，找出未翻译的key
    private static void findMissingOrUntranslatedKeysForMultipleLanguages(
            Map<String, String> defaultKeyValues,
            Map<String, Map<String, String>> targetLanguages,
            Map<String, Set<String>> excludedKeysMap
    ) {
        for (Map.Entry<String, Map<String, String>> entry : targetLanguages.entrySet()) {
            String language = entry.getKey();
            Map<String, String> targetKeyValues = entry.getValue();
            Set<String> excludedKeys = excludedKeysMap.getOrDefault(language, new HashSet<>());

            Set<String> missingOrUntranslatedKeys = new HashSet<>();

            // 找出目标语言中缺失的key
            for (String key : defaultKeyValues.keySet()) {
                if (excludedKeys.contains(key)) {
                    continue; // 跳过待排除的key
                }

                String defaultValue = defaultKeyValues.get(key);
                String targetValue = targetKeyValues.get(key);

                // 如果目标语言中没有这个key，或者值与默认语言中的值相同，则认为未翻译
                if (targetValue == null || (targetValue.indexOf("@string/") != 0 && targetValue.equals(defaultValue))) {
                    missingOrUntranslatedKeys.add(key);
                }
            }

            // 输出该语言的缺失或未翻译的key
            if (missingOrUntranslatedKeys.isEmpty()) {
                System.out.println(language + "语言：所有key均已翻译！");
            } else {
                System.out.println(language + "语言：未翻译或缺失的key如下：");
                for (String key : missingOrUntranslatedKeys) {
                    System.out.println(key);
                }
            }
            System.out.println("-----------------------------------");
        }
    }

    public static void main(String[] args) {
        // 默认语言的 strings.xml 文件路径
        File defaultStringsFile = new File("C:\\Projects\\oraimo-android\\module_resource\\src\\main\\res\\values\\strings.xml");

        // 目标语言的 strings.xml 文件路径 (例如ar, bn, fr, pt, zh)
        Map<String, File> targetLanguageFiles = new HashMap<>();
        targetLanguageFiles.put("ar", new File("C:\\Projects\\oraimo-android\\module_resource\\src\\main\\res\\values-ar\\strings.xml"));
        targetLanguageFiles.put("bn", new File("C:\\Projects\\oraimo-android\\module_resource\\src\\main\\res\\values-bn\\strings.xml"));
        targetLanguageFiles.put("fr", new File("C:\\Projects\\oraimo-android\\module_resource\\src\\main\\res\\values-fr\\strings.xml"));
        targetLanguageFiles.put("pt", new File("C:\\Projects\\oraimo-android\\module_resource\\src\\main\\res\\values-pt\\strings.xml"));


        // 待排除key的文件路径 (例如 exclude-ar.txt, exclude-fr.txt)
        Map<String, File> excludeFiles = new HashMap<>();
        excludeFiles.put("ar", new File("D:\\Projects\\AndroidRefactorTools\\temp\\exclude-ar.txt"));
        excludeFiles.put("bn", new File("D:\\Projects\\AndroidRefactorTools\\temp\\exclude-bn.txt"));
        excludeFiles.put("fr", new File("D:\\Projects\\AndroidRefactorTools\\temp\\exclude-fr.txt"));
        excludeFiles.put("pt", new File("D:\\Projects\\AndroidRefactorTools\\temp\\exclude-pt.txt"));
        excludeFiles.put("zh", new File("D:\\Projects\\AndroidRefactorTools\\temp\\exclude-zh.txt"));

        // 提取默认语言的所有key-value对
        Map<String, String> defaultKeyValues = extractKeysAndValuesFromStringsFile(defaultStringsFile);

        // 提取目标语言的所有key-value对
        Map<String, Map<String, String>> targetLanguages = new HashMap<>();
        for (Map.Entry<String, File> entry : targetLanguageFiles.entrySet()) {
            String language = entry.getKey();
            File file = entry.getValue();
            targetLanguages.put(language, extractKeysAndValuesFromStringsFile(file));
        }

        // 读取待排除的key
        Map<String, Set<String>> excludedKeysMap = new HashMap<>();
        for (Map.Entry<String, File> entry : excludeFiles.entrySet()) {
            String language = entry.getKey();
            File excludeFile = entry.getValue();
            excludedKeysMap.put(language, loadExcludedKeys(excludeFile));
        }

        // 比较默认语言和多个目标语言的key-value，找出缺失或未翻译的key
        findMissingOrUntranslatedKeysForMultipleLanguages(defaultKeyValues, targetLanguages, excludedKeysMap);
    }
}
